package com.cloudsigns.factorymanager2.engineering.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.IMediaListForPatrolMapForManagerView;
import com.cloudsigns.factorymanager2.engineering.IView.InRegionListView;
import com.cloudsigns.factorymanager2.engineering.adapter.DropDownPoupWindowAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.PopWindowAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.TableContentEngineeringInstallForManagerAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.TableLeftEngineeringInstallForManagerAdapter;
import com.cloudsigns.factorymanager2.engineering.bean.MediaBean;
import com.cloudsigns.factorymanager2.engineering.bean.OrderParentBean;
import com.cloudsigns.factorymanager2.engineering.bean.RegionBean;
import com.cloudsigns.factorymanager2.engineering.customview.SpinerPopWindow;
import com.cloudsigns.factorymanager2.engineering.presenter.MediaListForPatrolMapForManagerPresenter;
import com.cloudsigns.factorymanager2.engineering.presenter.RegionListPresenter;
import com.cloudsigns.factorymanager2.project.customview.DropDownPoupWindow;
import com.cloudsigns.factorymanager2.project.customview.NoscrollListView;
import com.cloudsigns.factorymanager2.project.customview.SyncHorizontalScrollView;
import com.cloudsigns.factorymanager2.project.myinerface.ItemClickListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.DateUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by tony on 2018/5/12.
 */

public class PatrolStatusTableForManagerActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, ItemClickListener, InRegionListView, IMediaListForPatrolMapForManagerView {
    private RelativeLayout rl_right;
//    private ImageView img_right;
    private TextView tv_title;
    private ViewGroup rl_back;
    private TextView tv_head_title;
    /*表头 日期*/
    private LinearLayout ll_head_date;
    private NoscrollListView lvLeft;
    private NoscrollListView lvData;
    private TableLeftEngineeringInstallForManagerAdapter mLeftAdapter;
    private TableContentEngineeringInstallForManagerAdapter mDataAdapter;
    private SyncHorizontalScrollView mHeaderHorizontal;
    private SyncHorizontalScrollView mDataHorizontal;
    private String TAG = PatrolStatusTableForManagerActivity.class.getSimpleName();

    private RegionListPresenter regionListPresenter;
    private MediaListForPatrolMapForManagerPresenter mediaListForPatrolMapForManagerPresenter;

    private String selectedRegionId = "";

    private SpinerPopWindow<String> regionPopwindow;
    private DropDownPoupWindowAdapter regionPopwindowAdapter;
    //    private PopWindowAdapter regionPopwindowAdapter;

    List<RegionBean> regionBeanList = new ArrayList<>();
    List<MediaBean> mediaBeanList = new ArrayList<>();
    List<String> tableHeadDataList = new ArrayList<>();

    private LayoutInflater layoutInflater;

//    List<MediaBean> tableLeftDataList = new ArrayList<>();

    //RegionDetailForManagerActivity

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_patrolstatus_for_manager);

        regionListPresenter = new RegionListPresenter(this);
        mediaListForPatrolMapForManagerPresenter = new MediaListForPatrolMapForManagerPresenter(this);
        init();

        regionListPresenter.getMediaRegionList();
    }

    private void init() {
        rl_right = findViewById(R.id.rl_right);
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
       // img_right = findViewById(R.id.img_right);

        tv_title.setText("巡查状态表");
       // img_right.setBackgroundResource(R.mipmap.title_icon_menu);
        rl_right.setVisibility(View.VISIBLE);
        rl_back.setOnClickListener(this);
        rl_right.setOnClickListener(this);

        tv_head_title = findViewById(R.id.tv_head_title);
        ll_head_date = findViewById(R.id.ll_head_date);
        lvLeft = (NoscrollListView) findViewById(R.id.lv_left);
        lvData = (NoscrollListView) findViewById(R.id.lv_data);
        mDataHorizontal = (SyncHorizontalScrollView) findViewById(R.id.data_horizontal);
        mHeaderHorizontal = (SyncHorizontalScrollView) findViewById(R.id.header_horizontal);

        /*实现两个scrollview联动*/
        mDataHorizontal.setScrollView(mHeaderHorizontal);
        mHeaderHorizontal.setScrollView(mDataHorizontal);

        mLeftAdapter = new TableLeftEngineeringInstallForManagerAdapter(this, TAG);
        mLeftAdapter.setData(mediaBeanList);
        lvLeft.setAdapter(mLeftAdapter);

        mDataAdapter = new TableContentEngineeringInstallForManagerAdapter(this, TAG);
        mDataAdapter.setData(mediaBeanList);
        mDataAdapter.setHeadData(tableHeadDataList);
        mDataAdapter.setOnclickListener(this);
        lvData.setAdapter(mDataAdapter);

        regionPopwindow = new SpinerPopWindow<String>(this, this);
        regionPopwindowAdapter = new DropDownPoupWindowAdapter(this, TAG);
        regionPopwindowAdapter.setData(regionBeanList);
        regionPopwindow.setAdapter(regionPopwindowAdapter);


        layoutInflater = getLayoutInflater();

        tv_head_title.setOnClickListener(this);
        tv_head_title.setTextColor(getResources().getColor(R.color.rgb_2F5597));
    }


    private void initData() {
        if (null != mediaBeanList) {

            tableHeadDataList.clear();

            /*初始化表的左边数据*/
            mLeftAdapter.setData(mediaBeanList);
            mLeftAdapter.notifyDataSetChanged();

            /* 初始化表头 计算所有点位中最小的反馈处理日期 到当前日期的天数 用来显示表头长度*/
            long minDate = -1;
            //long maxDate = -1;
            long maxDate = System.currentTimeMillis();

            if (null != mediaBeanList && mediaBeanList.size() > 0) {
                for (MediaBean mediaBean : mediaBeanList) {
                    if (minDate == -1) {
                        minDate = mediaBean.getHandleDate();
                    } else {
                        long date = mediaBean.getHandleDate();
                        if (date > 0 && date < minDate)
                            minDate = date;
                    }

//                        if (maxDate == -1) {
//                            maxDate = mediaBean.getFeedbackDate();
//                        } else {
//                            long date = mediaBean.getFeedbackDate();
//                            if (date > 0 && date > maxDate)
//                                maxDate = date;
//                        }

                }

                if (minDate <= 0) {
                    minDate = maxDate;
                }
            }


            if (minDate > 0 && maxDate > 0) {
                String m = DateUtil.getYyyy_Mm_Dd(minDate);
                minDate = DateUtil.getMillis(m);
//             long currentDate = System.currentTimeMillis();
                int days = DateUtil.getBetweenDays(minDate, maxDate);
                if (days >= 0) {
                    if (days < 6) {
                        days = 6;
                    }

                    tableHeadDataList.clear();

                    for (int i = 0; i <= days; i++) {
                        long nextDate = minDate + i * 24 * 60 * 60 * 1000;
                        tableHeadDataList.add(DateUtil.getYyyy_Mm_Dd(nextDate));
                    }
                }
            }

            updateTableHeadUi();

                /*初始化表格内容*/
            mDataAdapter.setData(mediaBeanList);
            mDataAdapter.setHeadData(tableHeadDataList);
            mDataAdapter.notifyDataSetChanged();


        }
    }


    private void getMediaList() {
        mediaListForPatrolMapForManagerPresenter.getPatrolMediaListForMap();
    }

    /**
     * 初始化表头
     */
    private void updateTableHeadUi() {
        if (null != tableHeadDataList) {


            ll_head_date.removeAllViews();

            for (String date : tableHeadDataList) {
                View view = layoutInflater.inflate(R.layout.item_table_head_week_patrol, null);
                TextView tv_week_head = view.findViewById(R.id.tv_week_head);
                TextView tv_year_head = view.findViewById(R.id.tv_year_head);

                tv_year_head.setText(date.substring(5, date.length()));
                tv_week_head.setText(DateUtil.getWeekByDateStr(date));
                ll_head_date.addView(view);
            }
        }

    }


    /**
     * 设置添加屏幕的背景透明�?
     *
     * @param bgAlpha
     */
    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    private void showRegionPop(View view) {
        if (null != regionPopwindow)
            regionPopwindow.dismiss();

        regionPopwindow.setWidth(view.getWidth() * 2);
//        popwindow.showAsDropDown(anchor);
        regionPopwindow.showAsDropDown(view, view.getLayoutParams().width / 2, 5);
    }


    @Override
    public void itemClick(View view, int position) {
        Intent mIntent;
        MediaBean mediaBean = (MediaBean) view.getTag();
        if (null != mediaBean) {
            CommonEnum.FeedBackState feedBackState = mediaBean.getState();
            if (null != feedBackState) {
                if (feedBackState == CommonEnum.FeedBackState.WAIT_CONFIRM) {
                    mIntent = new Intent(PatrolStatusTableForManagerActivity.this, PatrolFeedBackDetailForWaitStatuActivity.class);
                    mIntent.putExtra(ConstantUtil.KEY_1, TAG);
                    mIntent.putExtra(ConstantUtil.KEY_2, mediaBean);
                    startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                } else if (feedBackState == CommonEnum.FeedBackState.EXCEPTION) {
                    mIntent = new Intent(PatrolStatusTableForManagerActivity.this, PatrolFeedBackDetailForExceptionStatuActivity.class);
                    mIntent.putExtra(ConstantUtil.KEY_1, TAG);
                    mIntent.putExtra(ConstantUtil.KEY_2, mediaBean);
                    startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                }
            }


        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        if (i < regionBeanList.size()) {
            if (null != regionPopwindow)
                regionPopwindow.dismiss();

            RegionBean regionBean = regionBeanList.get(i);
            if (!regionBean.getId().equals(selectedRegionId)) {
                selectedRegionId = regionBean.getId();
                tv_head_title.setText(regionBean.getRegionName());

                getMediaList();
            }

        }

    }

    @Override
    public void onClick(View view) {
        Intent mIntent;
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_right:
                showRegionPop(view);
                break;
            case R.id.tv_head_title:
                mIntent = new Intent(PatrolStatusTableForManagerActivity.this, RegionPatrolOrderListActivity.class);
                mIntent.putExtra(ConstantUtil.KEY_1, TAG);
                mIntent.putExtra(ConstantUtil.KEY_2, selectedRegionId);
                mIntent.putExtra("regionName", tv_head_title.getText().toString().trim());
                startActivity(mIntent);
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (null != data) {
            switch (requestCode) {
                case ConstantUtil.START_ACTIVITY_KEY_1:
                    if (null != data)
                        mediaListForPatrolMapForManagerPresenter.getPatrolMediaListForMap();
                    break;
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (regionPopwindow != null) {
            regionPopwindow.dismiss();
            regionPopwindow = null;
        }

    }


    @Override
    public void getMediaRegionListSuccessed(List<RegionBean> banList) {
        if (null != banList) {
            regionBeanList.clear();
            regionBeanList.addAll(banList);

            regionPopwindowAdapter.setData(regionBeanList);
            regionPopwindowAdapter.notifyDataSetChanged();

            if (regionBeanList.size() > 0) {

                RegionBean regionBean = regionBeanList.get(0);
                selectedRegionId = regionBean.getId();
                tv_head_title.setText(regionBean.getRegionName());

                getMediaList();
            }

        }
    }

    @Override
    public String getId() {

        return selectedRegionId;
    }

    @Override
    public void getPatrolMediaListForMapSuccessed(List<MediaBean> beanList) {
        if (null != beanList) {
            mediaBeanList.clear();
            mediaBeanList.addAll(beanList);

            initData();
        }
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }


}
